import axios from 'axios'
import { refreshToken } from './login'

export const http = axios.create({
  baseURL: 'https://gitee.com/api/v5/gists'
})

/**
 * 请求拦截
 */
http.interceptors.request.use(
  (config) => {
    const method = config.method || 'get'
    let key: 'data' | 'params' | undefined
    if (['get'].includes(method)) key = 'params'
    if (['patch', 'post'].includes(method)) key = 'data'
    if (key) {
      config[key] = {
        ...(config[key] as {}),
        access_token: localStorage.gitee_access_token
      }
      return config
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 * 响应拦截
 */
http.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response.status === 401) {
      return refreshToken().then(() => {
        return http(error.config)
      })
    }
    return Promise.reject(error)
  }
)
